<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
/**
 * 获取随机字符串
 * @param int $len 获取字符长度  默认5位 最高32位
 * @param int $type 字符串类型 [0:含特殊字符【默认】|1:不含特殊字符]
 * @return string
 */
function getRandomStr($len=5, $type=0)
{
    $len = $len<=0 ?  5 : $len;
    $len = $len>32 ? 32 : $len;
    switch ($type) {
        case 1:
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            break;
        case 2:
            $chars = '0123456789';
            break;
        default:
            $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()+-';
    }
    $str = '';
    for ($i=0;$i<$len;$i++) {
        $str .= $chars[mt_rand(0, strlen($chars)-1)];
    }
    return $str;
}

/**
 * @param $string
 * @param string $operation
 * @param string $key
 * @param int $expiry
 * @return bool|string
 */
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
    // 动态密匙长度，相同的明文会生成不同密文就是依靠动态密匙
    $ckey_length = 4;

    // 密匙
    $key = md5($key ? $key : 'qazwsxedcrfvtgbyhnujmikolp');

    // 密匙a会参与加解密
    $keya = md5(substr($key, 0, 16));
    // 密匙b会用来做数据完整性验证
    $keyb = md5(substr($key, 16, 16));
    // 密匙c用于变化生成的密文
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';
    // 参与运算的密匙
    $cryptkey = $keya.md5($keya.$keyc);
    $key_length = strlen($cryptkey);
    // 明文，前10位用来保存时间戳，解密时验证数据有效性，10到26位用来保存$keyb(密匙b)，
    //解密时会通过这个密匙验证数据完整性
    // 如果是解码的话，会从第$ckey_length位开始，因为密文前$ckey_length位保存 动态密匙，以保证解密正确
    $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) :
        sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
    $string_length = strlen($string);
    $result = '';
    $box = range(0, 255);
    $rndkey = array();
    // 产生密匙簿
    for($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }
    // 用固定的算法，打乱密匙簿，增加随机性，好像很复杂，实际上对并不会增加密文的强度
    for($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }
    // 核心加解密部分
    for($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        // 从密匙簿得出密匙进行异或，再转成字符
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }
    if($operation == 'DECODE') {
        // 验证数据有效性，请看未加密明文的格式
        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) &&
            substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        // 把动态密匙保存在密文里，这也是为什么同样的明文，生产不同密文后能解密的原因
        // 因为加密后的密文可能是一些特殊字符，复制过程可能会丢失，所以用base64编码
        return $keyc.str_replace('=', '', base64_encode($result));
    }
}


/**
 * 验证电话号码格式正确性
 * @param $number 手机号
 * @param int $type 类型 [1:手机【默认】|2:座机|3:座机+手机]
 * @return bool
 */
function checkTel($number, $type=1)
{
    $result = false;
    switch ($type) {
        case 1:
            //手机
            if (preg_match(config('regular_mobile'), $number)) {
                $result = true;
            }
            break;
        case 2:
            //座机
            if (preg_match(config('regular_tel'), $number)) {
                $result = true;
            }
            break;
        case 3:
            //座机+手机
            if (preg_match(config('regular_mobile'), $number) || preg_match(config('regular_tel'), $number)) {
                $result = true;
            }
            break;
    }
    return $result;
}

/**
 * 验证邮箱格式
 * @param $email 邮箱地址
 * @return bool
 */
function checkEmail($email)
{
    $result = false;
    if (preg_match(config('regular.email'), $email)) {
        $result = true;
    }
    return $result;
}

/**
 * 金额保留两位小数(舍)
 * @param $amount
 * @return string
 */
function amountFormat($amount) {
    $amount = floatval(sprintf("%.3f",$amount));
    $amountSplit = explode('.', $amount);
    $decimal = '00';

    if (isset($amountSplit[1])) {
        if (strlen($amountSplit[1]) == 1) {
            $decimal = sprintf('%d0', $amountSplit[1]);
        } else {
            $decimal = substr($amountSplit[1], 0, 2);
        }
    }

    return sprintf('%s.%s', $amountSplit[0], $decimal);
}

function createDir($path) {
    !is_dir($path) && mkdir($path, 0777, true);
}

/**
 * 模拟post提交
 * @param string $url 地址
 * @param array|null|string $xdts 提交的数据
 * @param int $type
 * @return mixed|string
 */
function _https_post($url,$xdts = null){
    $curl = curl_init();
    curl_setopt($curl,CURLOPT_URL,$url);
    curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
    curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
    curl_setopt($curl,CURLOPT_POST,1);
    curl_setopt($curl,CURLOPT_POSTFIELDS,$xdts);
    curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
    #curl_setopt($curl,CURLOPT_BINARYTRANSFER,1);
    $result = curl_exec($curl);
    if (curl_errno($curl)) {
        return 'Errno'.curl_error($curl);
    }
    curl_close($curl);
    return $result;
}

/**
 * curl获取页面
 * @param  string  $url         页面地址
 * @param  array   $header      http头信息    默认为空
 */
function get_page($url,$header=''){
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSLVERSION, 4);
    curl_setopt($ch, CURLOPT_SSL_CIPHER_LIST, 'SSLv3');
    if ($header) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        preg_match('/Accept-Encoding:(.+?)---ly---/is', implode('---ly---', $header), $encoding);
        if (!empty($encoding[0])) {
            curl_setopt($ch, CURLOPT_ENCODING, $encoding[1]);
        }
    }
    curl_setopt($ch, CURLOPT_URL, $url);
    $res = curl_exec($ch);
    if ($res === false) {
        echo 'Curl error: ' . curl_error($ch).'<br>'.$url.'<br>';
    } else {
        return mb_convert_encoding($res, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5' );
    }
}

/**
 * 生成订单号
 * @param string $prefix 前缀
 * @return string
 */
function createOrderNo($prefix='') {
    return sprintf('%s%s%s', $prefix, date('YmdHis'), mt_rand(1000,9999));
}

/**
 * 把返回的数据集转换成Tree
 * @access public
 * @param array $list 要转换的数据集
 * @param string $pk 主键
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 *
 * 实例：
 *      请求数据
 *          list_to_tree([['id' => 1, 'pid' => 0, 'name' => 'dsa0'], ['id' => 2, 'pid' => 0, 'name' => 'dsa0'], ['id' => 3, 'pid' => 1, 'name' => 'dsa1'], ['id' => 4, 'pid' => 3, 'name' => 'dsa1'], ['id' => 5, 'pid' => 2, 'name' => 'dsa2'], ['id' => 6, 'pid' => 1, 'name' => 'dsa1'],])
 *      返回数据json
 *          [{"id":1,"pid":0,"name":"dsa0","_child":[{"id":3,"pid":1,"name":"dsa1","_child":[{"id":4,"pid":3,"name":"dsa1"}]},{"id":6,"pid":1,"name":"dsa1"}]},{"id":2,"pid":0,"name":"dsa0","_child":[{"id":5,"pid":2,"name":"dsa2"}]}]
 */
function list_to_tree($list, $pk='id',$pid = 'pid',$child = '_child',$root=0) {
    // 创建Tree
    $tree = [];
    if(is_array($list)) {
        // 创建基于主键的数组引用
        $refer = [];
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 对查询结果集进行排序
 * @access public
 * @param array $list 查询结果
 * @param string $field 排序的字段名
 * @param array $sortby 排序类型
 * asc正向排序 desc逆向排序 nat自然排序
 * @return array
 */
function list_sort_by($list,$field, $sortby='asc') {
    if(is_array($list)){
        $refer = $resultSet = [];
        foreach ($list as $i => $data) {
            $refer[$i] = &$data[$field];
        }
        switch ($sortby) {
            case 'asc': // 正向排序
                asort($refer);
                break;
            case 'desc':// 逆向排序
                arsort($refer);
                break;
            case 'nat': // 自然排序
                natcasesort($refer);
                break;
        }
        foreach ( $refer as $key=> $val) {
            $resultSet[] = &$list[$key];
        }
        return $resultSet;
    }
    return false;
}

function pdf($content, $header='进销存TCPDF')
{
    //引用第三方库
    vendor('tcpdf.tcpdf');
    $pdf = new \Tcpdf(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    // 设置打印模式
    $pdf->SetCreator(PDF_CREATOR);
    $pdf->SetAuthor('**科技');
    $pdf->SetTitle($header);
    $pdf->SetSubject('进销存');
    $pdf->SetKeywords('TCPDF, PDF, 进销存,');
    // 是否显示页眉
    $pdf->setPrintHeader(false);
    // 设置页眉显示的内容s
    $pdf->SetHeaderData('logo.png', 60, 'www.jete.cn', '标题', [0,64,255], [0,64,128]);
    // 设置页眉字体
    $pdf->setHeaderFont(['dejavusans', '', '12']);
    // 页眉距离顶部的距离
    $pdf->SetHeaderMargin('5');
    // 是否显示页脚
    $pdf->setPrintFooter(true);
    // 设置页脚显示的内容
    $pdf->setFooterData([0,64,0], [0,64,128]);
    // 设置页脚的字体
    $pdf->setFooterFont(['dejavusans', '', '10']);
    // 设置页脚距离底部的距离
    $pdf->SetFooterMargin('10');
    // 设置默认等宽字体
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
    // 设置行高
    $pdf->setCellHeightRatio(1);
    // 设置左、上、右的间距
    $pdf->SetMargins('10', '10', '10');
    // 设置是否自动分页  距离底部多少距离时分页
    $pdf->SetAutoPageBreak(TRUE, '15');
    // 设置图像比例因子
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
    if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
        require_once(dirname(__FILE__).'/lang/eng.php');
        $pdf->setLanguageArray($l);
    }
    $pdf->setFontSubsetting(true);
    $pdf->AddPage();
    // 设置字体
    $pdf->SetFont('stsongstdlight', '', 14, '', true);
    $pdf->writeHTMLCell(0, 0, '', '', $content, 0, 1, 0, true, '', true);
    $pdf->Output('example_001.pdf', 'I');
}

/**
 * 数组转xls格式的excel文件
 * @param  array  $data      需要生成excel文件的数组
 * @param  string $filename  生成的excel文件名
 * @param  string $title   表名
 *      示例数据：
$data = array(
array(NULL, 2010, 2011, 2012),
array('Q1',   12,   15,   21),
array('Q2',   56,   73,   86),
array('Q3',   52,   61,   69),
array('Q4',   30,   32,    0),
);
 */
function create_xls($data, $filename='simple.xls', $title='Sheet1'){
    ini_set('max_execution_time', '0');
    Vendor('PHPExcel.PHPExcel');
    $filename=str_replace('.xls', '', $filename).'.xls';
    $phpexcel = new PHPExcel();
//    $phpexcel->getProperties()
//        ->setCreator("Maarten Balliauw")
//        ->setLastModifiedBy("Maarten Balliauw")
//        ->setTitle("Office 2007 XLSX Test Document")
//        ->setSubject("Office 2007 XLSX Test Document")
//        ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
//        ->setKeywords("office 2007 openxml php")
//        ->setCategory("Test result file");
    $phpexcel->getProperties()
        ->setCreator("**科技")
        ->setLastModifiedBy("**科技")
        ->setTitle($title)
        ->setSubject($title)
        ->setDescription("**科技进销存管理系统")
        ->setKeywords("**科技，进销存，")
        ->setCategory("数据报表");

    $phpexcel->getActiveSheet()->fromArray($data);
    $phpexcel->getActiveSheet()->setTitle($title);
    $phpexcel->setActiveSheetIndex(0);

    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=$filename");
    header('Cache-Control: max-age=0');
    header('Cache-Control: max-age=1');
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
    $objwriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
    $objwriter->save('php://output');
    exit;
}

/**
 * 数据转csv格式的excle
 * @param  array $data      需要转的数组
 * @param  string $header   要生成的excel表头
 * @param  string $filename 生成的excel文件名
 *      示例数组：
$data = array(
'1,2,3,4,5',
'6,7,8,9,0',
'1,3,5,6,7'
);
$header='用户名,密码,头像,性别,手机号';
 */
function create_csv($data,$header=null,$filename='simple.csv'){
    // 如果手动设置表头；则放在第一行
    if (!is_null($header)) {
        array_unshift($data, $header);
    }
    // 防止没有添加文件后缀
    $filename = sprintf('%s.csv', str_replace('.csv', '', $filename));
    ob_clean();
    Header( "Content-type:  application/octet-stream ");
    Header( "Accept-Ranges:  bytes ");
    Header( "Content-Disposition:  attachment;  filename=$filename");
    foreach( $data as $k => $v){
        // 如果是二维数组；转成一维
        if (is_array($v)) {
            $v=implode(',', $v);
        }
        // 替换掉换行
        $v=preg_replace('/\s*/', '', $v);
        // 解决导出的数字会显示成科学计数法的问题
        $v=str_replace(',', "\t,", $v);
        // 转成gbk以兼容office乱码的问题
        echo sprintf("%s\t\r\n", iconv('UTF-8','GBK',$v));
    }
}

/**
 * 跳向支付宝付款
 * @param  array $order 订单数据 必须包含 out_trade_no(订单号)、price(订单金额)、subject(商品名称标题)
 */
function alipay($order){
    vendor('Alipay.AlipaySubmit', '', '.class.php');
    // 获取配置
    $config = config('alipay.pay');
    $data = [
        "_input_charset" => $config['input_charset'], // 编码格式
        "logistics_fee" => "0.00", // 物流费用
        "logistics_payment" => "SELLER_PAY", // 物流支付方式SELLER_PAY（卖家承担运费）、BUYER_PAY（买家承担运费）
        "logistics_type" => "EXPRESS", // 物流类型EXPRESS（快递）、POST（平邮）、EMS（EMS）
        "notify_url" => $config['notify_url'], // 异步接收支付状态通知的链接
        "out_trade_no" => $order['out_trade_no'], // 订单号
        "partner" => $config['partner'], // partner 从支付宝商户版个人中心获取
        "payment_type" => "1", // 支付类型对应请求时的 payment_type 参数,原样返回。固定设置为1即可
        "price" => $order['price'], // 订单价格单位为元
        // "price" => 0.01, // // 调价用于测试
        "quantity" => "1", // price、quantity 能代替 total_fee。 即存在 total_fee,就不能存在 price 和 quantity;存在 price、quantity, 就不能存在 total_fee。 （没绕明白；好吧；那无视这个参数即可）
        "receive_address" => '1', // 收货人地址 即时到账方式无视此参数即可
        "receive_mobile" => '1', // 收货人手机号码 即时到账方式无视即可
        "receive_name" => '1', // 收货人姓名 即时到账方式无视即可
        "receive_zip" => '1', // 收货人邮编 即时到账方式无视即可
        "return_url" => $config['return_url'], // 页面跳转 同步通知 页面路径 支付宝处理完请求后,当前页面自 动跳转到商户网站里指定页面的 http 路径。
        "seller_email" => $config['seller_email'], // email 从支付宝商户版个人中心获取
        "service" => "create_direct_pay_by_user", // 接口名称 固定设置为create_direct_pay_by_user
        "show_url" => $config['show_url'], // 商品展示网址,收银台页面上,商品展示的超链接。
        "subject" => $order['subject'] // 商品名称商品的标题/交易标题/订单标 题/订单关键字等
    ];
    $alipay=new \AlipaySubmit($config);
    $new=$alipay->buildRequestPara($data);
    $go_pay=$alipay->buildRequestForm($new, 'get','支付');
    echo $go_pay;
}

/**
 * 微信扫码支付
 * @param  array $order 订单 必须包含支付所需要的参数 body(产品描述)、total_fee(订单金额)、out_trade_no(订单号)、product_id(产品id)
 */
function weixinpay($order){
    $order['trade_type']='NATIVE';
    Vendor('Weixinpay.Weixinpay');
    $weixinpay=new \Weixinpay();
    $weixinpay->pay($order);
}

/**
 * 用户密码加密
 * @param $str
 * @param string $key
 * @return string
 */
function passmd($str , $key = 'hadNkAIZqB1cK#DPW6pjaSbUda8$Luq8')
{
    return '' === $str ? '' : md5(sha1($str) . $key);
}


function goods_class_nav($data){

    echo '<ul class="nav nav-second-level">';
    foreach ($data as $k=>$v){
        if(count($v['class']) > 0){
            echo '<li><a href="#">'.$v['html'].$v['classname'].'<span class="fa arrow"></span></a>';
            goods_class_nav($v['class']);
            echo '</li>';
        }else{
            echo '<li><a class="J_menuItem" href="'.url('Goods/index',array('goodsclass_id'=>$v['id'])).'">'.$v['html'].$v['classname'].'</a></li>';
        }
    }
    echo '</ul>';
    return;

}

function new_class_nav($data){

    echo '<ul class="nav nav-second-level">';
    foreach ($data as $k=>$v){
        if(count($v['class']) > 0){
            echo '<li><a href="#">'.$v['html'].$v['classname'].'<span class="fa arrow"></span></a>';
            new_class_nav($v['class']);
            echo '</li>';
        }else{
            echo '<li><a class="J_menuItem" href="'.url('News/index',array('newclass_id'=>$v['id'])).'">'.$v['html'].$v['classname'].'</a></li>';
        }
    }
    echo '</ul>';
    return;

}



function linkKJ($data,$ontrue=false,$goodsclass,$newclass){

    foreach ($data as $k=>$v){
        if(count($v['class']) > 0){
            if($ontrue){
                echo '<li><a href="'.url(''.$v['controller'].'/'.$v['action'].'', $v['params']).'">'.$v['html'].$v['title'].'<span class="fa arrow"></span></a>';
            }else{
                echo '<li><a href="'.url(''.$v['controller'].'/'.$v['action'].'', $v['params']).'"><i class="fa fa fa-'.$v['ico'].'"></i><span class="nav-label">'.$v['html'].$v['title'].'</span><span class="fa arrow"></span></a>';
            }
            echo '<ul class="nav nav-second-level">';
            linkKJ($v['class'],true,$goodsclass,$newclass);
            echo '</ul>';
            echo '</li>';
        }else{
            if($ontrue){
                if($v['controller'] == 'Goods'){ //如果是产品分类
                    goods_class_nav($goodsclass);
                }else if($v['controller'] == 'News'){ //如果是文章分类
                    new_class_nav($newclass);
                }else{
                    echo '<li><a class="J_menuItem" href="'.url(''.$v['controller'].'/'.$v['action'].'', $v['params']).'">'.$v['html'].$v['title'].'</a></li>';
                }
            }else{
                echo '<li><a class="J_menuItem" href="'.url(''.$v['controller'].'/'.$v['action'].'', $v['params']).'"><i class="fa fa fa-'.$v['ico'].'"></i><span class="nav-label">'.$v['html'].$v['title'].'</span></a></li>';
            }
        }
    }
    return;
}

/*
 * 多维数组组合
 * */
function classnav($data, $pid = 0)
{
    $arr = array();
    foreach ($data as $v) {
        if ($v['pid'] == $pid) {
            $v['class'] = classnav($data, $v['id']);
            $arr[] = $v;
        }
    }
    return $arr;
}

/*
 * @ system专用无限极分类排序组合
 * @ param array $data 要排序组合的数据
 * @ param int $pid 顶级id
 * @ param int $level html内容组装的次数
 * @ param string $html 排序后前面的标识
 * @ return 返回组合好的多维数组
 */
function systemNav($data, $pid = 0, $level=0, $html = "&nbsp;&nbsp;&nbsp;")
{

    static $arr = array();
    foreach ($data as $v) {
        if ($v['pid'] == $pid) {
            $v['html'] = str_repeat($html, $level);
            $arr[] = $v;
            systemNav($data, $v['id'], $level + 1);
        }
    }
    return $arr;
}

/*
 * @ system专用无限极分类排序组合
 * @ param array $data 要排序组合的数据
 * @ param int $pid 顶级id
 * @ param int $level html内容组装的次数
 * @ param string $html 排序后前面的标识
 * @ return 返回组合好的多维数组
 */
function newClassNav($data, $pid = 0, $level=0, $html = "&nbsp;&nbsp;&nbsp;")
{
    static $arr = array();
    foreach ($data as $v) {
        if ($v['pid'] == $pid) {
            $v['html'] = str_repeat($html, $level);
            $arr[] = $v;
            newClassNav($data, $v['id'], $level + 1);
        }
    }
    return $arr;
}

/*
 * @ system专用无限极分类排序组合
 * @ param array $data 要排序组合的数据
 * @ param int $pid 顶级id
 * @ param int $level html内容组装的次数
 * @ param string $html 排序后前面的标识
 * @ return 返回组合好的多维数组
 */
function goodsClassNav($data, $pid = 0, $level=0, $html = "&nbsp;&nbsp;&nbsp;")
{

    static $arr = array();
    foreach ($data as $v) {
        if ($v['pid'] == $pid) {
            $v['html'] = str_repeat($html, $level);
            $arr[] = $v;
            goodsClassNav($data, $v['id'], $level + 1);
        }
    }
    return $arr;
}

function obj2array($data) {
    $datas = [];
    foreach ($data as $v) {
        if (is_object($v)) {
            $datas[] = $v->toArray();
        }
    }
    return $datas;
}

function nav($data,$true=false){

    if($true){
        echo '<ul style="padding:0;" >';
    }else{
        echo '<ul style="padding:0;" class="hierarchyOne">';
    }

    foreach ($data as $k=>$v){
        if ($v['checked']) {
            echo '<li><div class="checkbox">' . $v['html'] . '<label><input type="checkbox" checked name="link[][id]" style="margin-top:3px;" value="' . $v['id'] . '" onclick="check(this);" controller="' . $v['controller'] . '" /> <i></i> ' . $v['title'] . '</label></div>';
        } else {
            echo '<li><div class="checkbox">' . $v['html'] . '<label><input type="checkbox" name="link[][id]" style="margin-top:3px;" value="' . $v['id'] . '" onclick="check(this);" controller="' . $v['controller'] . '" /> <i></i> ' . $v['title'] . '</label></div>';
        }

        if(count($v['class']) > 0){
            nav($v['class'],true);
        }

        echo '</li>';
    }

    echo '</ul>';

    return;
}

/**
 * 文件上传
 */
function myUpload()
{
    $arr = [] ;
    require_once './Image.class.php';
    foreach ($_FILES as $k => $v) {
        if(! $_FILES[$k]['size']) continue;

        $ext = pathinfo($v['name'], PATHINFO_EXTENSION);
        if (!in_array(strtolower($ext), ['jpg','gif','png','jpeg','swf','bmp'])) {
            continue;
        }

        $file = request()->file($k);
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
       
        if($info){
            $thisFileName = DS .'uploads' . DS . $info->getSaveName();
           
            $thisFileName = str_replace('\\', '/', $thisFileName);
            $arr[] = $thisFileName;
            //压缩图片
            $src = '.' . $thisFileName;
            
            // if (strpos($v['type'], 'image/') == 0 && filesize($src) > 819200) {
            //     $image = new \Image();
            //     $image->percent = 1;
            //     $image->openImage($src);
            //     $image->thumpImage();
            //     $image->saveImage($src);
            // }
            // dump($image);
        } else {
            return false;
        }
    }
   
    return $arr;

}

function nav_group($data,$true=false){

    if($true){
        echo '<ul style="padding:0px;" >';
    }else{
        echo '<ul style="padding:0px;" class="hierarchyOne">';
    }

    foreach ($data as $k=>$v){

        if($v['checked'] == true){
            echo '<li><div class="checkbox">'.$v['html'].'<label><input type="checkbox" name="link[][id]" style="margin-top:3px;" value="'.$v['id'].'" onclick="check(this);" controller="'.$v['controller'].'" checked="checked" /> <i></i> '.$v['title'].'</label></div>';
        }else{
            echo '<li><div class="checkbox">'.$v['html'].'<label><input type="checkbox" name="link[][id]" style="margin-top:3px;" value="'.$v['id'].'" onclick="check(this);" controller="'.$v['controller'].'" /> <i></i> '.$v['title'].'</label></div>';
        }

        if(count($v['class']) > 0){
            nav($v['class'],true);
        }

        echo '</li>';
    }

    echo '</ul>';

    return;
}

/*
     * @ 取得当前分类的所以下级分类
     * @ param array $data 所有的分类数据
     * @ param int $id 当前分类的id
     * @ return 返回当前id的所有下级分类
     * */
function classification($data, $id, $if = 1)
{
    static $arr = array();
    foreach ($data as $v) {
        is_object($v) && $v = $v->toArray();
        if ($v['pid'] == $id) {
            $arr[] = $v['id'];
            classification($data, $v['id'], 0);
        }
    }

    // 非递归才运行，返回后把静态数组清空才备下次调用
    if ($if) {
        $array = $arr;
        $arr = array();
        return $array;
    }
}

/*
 * @ 无限极分类排序组合
 * @ param array $data 要排序组合的数据
 * @ param int $pid 顶级id
 * @ param int $level html内容组装的次数
 * @ param string $html 排序后前面的标识
 * @ return 返回组合好的多维数组
 */
function classsorting($data, $pid = 0, $level=0, $html = "<b style='font-size:16px;'>↑__</b>")
{
    static $arr = array();
    foreach ($data as $v) {
        is_object($v) && $v = $v->toArray();
        if ($v['pid'] == $pid) {
            $v['html'] = str_repeat($html, $level);
            $v['hierarchy'] = $level; //循环的层级
            $arr[] = $v;
            classsorting($data, $v['id'], $level + 1);
        }
    }
    return $arr;
}

/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '') {
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}

function isAjaxPost() {
    return request()->isAjax() && request()->isPost();
}

/**
 * @　GET 请求方式
 * @ param string $url 请求的地址
 * @ param string $data 请求的参数，一半都为空
 * */
function Get($url,$data=[]){
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
    //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $file_contents = curl_exec($ch);
    curl_close($ch);
    return json_decode($file_contents,true);
}

/**
 * @param $data 二维码包含的文字内容
 * @param $filename 保存二维码输出的文件名称，*.png
 * @param bool $picPath 二维码输出的路径
 * @param bool $logo 二维码中包含的LOGO图片路径
 * @param string $bgColor 二维码背景色
 * @param string $color 二维码点颜色
 * @param int $size 二维码的大小
 * @param string $level 二维码编码纠错级别：L、M、Q、H
 * @param int $padding 二维码边框的间距
 * @param bool $saveandprint 是否保存到文件并在浏览器直接输出，true:同时保存和输出，false:只保存文件
 * @return string
 */
function myqrcode($data, $filename, $picPath = false, $logo = false, $bgColor='#ffffff', $color='#000000', $size = 15, $level = 'L', $padding = 2, $saveandprint = true) {
    vendor("phpqrcode.phpqrcode"); //引入工具包
    // 下面注释了把二维码图片保存到本地的代码,如果要保存图片,用$fileName替换第二个参数false
    $qrcode = new \QRcode();
    $path = $picPath ? $picPath : "./uploads/".date('Ymd'); //图片输出路径
    if (!file_exists($path)) {
        mkdir($path,0777,true);
    }
    $logo = !empty($logo) && file_exists($logo) ? $logo : false;
    //在二维码上面添加LOGO
    if (empty($logo) || $logo === false) { //不包含LOGO
        if ($filename == false) {
            $qrcode->png($data, $filename, $level, $size, $padding, $saveandprint, $bgColor, $color); //直接输出到浏览器，不含LOGO
        } else {
            $filename = $path . '/' . $filename; //合成路径
            $qrcode->png($data, $filename, $level, $size, $padding, $saveandprint, $bgColor, $color); //直接输出到浏览器，不含LOGO
        }
    } else { //包含LOGO
        if ($filename == false) {
            //$filename=tempnam('','').'.png';//生成临时文件
            die('参数错误');
        } else {
            //生成二维码,保存到文件
            $filename = $path . '/' . $filename; //合成路径
        }
        $qrcode->png($data, $filename, $level, $size, $padding, $saveandprint, $bgColor, $color);
        $QR = imagecreatefromstring(file_get_contents($filename));
        $logo = imagecreatefromstring(file_get_contents($logo));
        $QR_width = imagesx($QR);
        $QR_height = imagesy($QR);
        $logo_width = imagesx($logo);
        $logo_height = imagesy($logo);
        $logo_qr_width = $QR_width / 5;
        $scale = $logo_width / $logo_qr_width;
        $logo_qr_height = $logo_height / $scale;
        $from_width = ($QR_width - $logo_qr_width) / 2;
        imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
        if ($filename === false) {
            Header("Content-type: image/png");
            imagepng($QR);
        } else {
            if ($saveandprint === true) {
                imagepng($QR, $filename);
                //header("Content-type: image/png"); //输出到浏览器
                //imagepng($QR);
            } else {
                imagepng($QR, $filename);
            }
        }
    }

    return $filename;
}

function fxqrcode($qrcode, $bg=false, $head_img=false) {
    if (!file_exists($bg)) {
        //$filename=tempnam('','').'.png';//生成临时文件
        die('参数错误');
    } else {
        //生成二维码,保存到文件
        $filename = $qrcode; //合成路径
    }
    $QR = imagecreatefromstring(file_get_contents($bg));
    $logo = imagecreatefromstring(file_get_contents($qrcode));
    $QR_width = imagesx($QR);
    $QR_height = imagesy($QR);
    $logo_width = imagesx($logo);
    $logo_height = imagesy($logo);
    $logo_qr_width = $QR_width / 1.5;
    $scale = $logo_width / $logo_qr_width;
    $logo_qr_height = $logo_height / $scale;
    $from_width = ($QR_width - $logo_qr_width) / 2;
    $from_height = ($QR_height - $logo_qr_height) / 2;
    imagecopyresampled($QR, $logo, $from_width, $from_height, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
    $head_img = '.'.$head_img;
    if (!file_exists($head_img)) {
        Header("Content-type: image/png");
        imagepng($QR);die;
    }
    $head_img = yuan_img($head_img);
    $temp_name =  __DIR__.'/../runtime/temp/'.time().mt_rand(100000,999999).'.png';
    imagepng($head_img, $temp_name);
    $head = imagecreatefromstring(file_get_contents($temp_name));
    $head_width = imagesx($head);
    $head_height = imagesy($head);
    $head_qr_width = $QR_width / 1.5;
    $scale = $head_width / $head_qr_width;
    imagecopyresampled($QR, $head, 480, 190, 0, 0, 278, 278, 100, 100);
    unlink($temp_name);
    imagepng($QR, $filename);
    return $filename;
}
/**
 * 将图片裁剪为圆形的图片
 * @param string 图片的Url地址  	$url
 * @param string 保存的新的url地址  	$path
 */
function circularImg($url, $path){
    $w = 270;  $h=270; // original size
    $original_path= $url;
    $src = imagecreatefromstring(file_get_contents($original_path));
    $newpic = imagecreatetruecolor($w,$h);
    imagealphablending($newpic,false);
    $transparent = imagecolorallocatealpha($newpic, 0, 0, 0, 127);
    $r=$w/2;
    for($x=0;$x<$w;$x++)
        for($y=0;$y<$h;$y++){
            $c = imagecolorat($src,$x,$y);
            $_x = $x - $w/2;
            $_y = $y - $h/2;
            if((($_x*$_x) + ($_y*$_y)) < ($r*$r)){
                imagesetpixel($newpic,$x,$y,$c);
            }else{
                imagesetpixel($newpic,$x,$y,$transparent);
            }
        }
    imagesavealpha($newpic, true);
    imagepng($newpic, $path);
    imagedestroy($newpic);
    imagedestroy($src);
    // unlink($url);
    return $path;
}
/**
 * 发短信验证码
 * @param $tel
 * @param $code
 * @param int $min
 * @param string $tpl_name
 * @return bool
 */
function sendAliMsg($tel, array $data, $tpl_name){
//    require_once '../aliyun/demo/sendSms.php';
//    foreach ($data as $k=>$v) {
//        $data[$k] = $v.'';
//    }
//    return sendSms($tel.'', $data, $tpl_name);
}

function sendMsg($tel, $content) {
    $client = new SoapClient('https://sdk2.028lk.com/sdk2/LinkWS.asmx?wsdl', array(
        'encoding' => 'UTF-8'
    ));
    $sendParam = array(
        'CorpID' => 'CQJS004761', //账号
        'Pwd' => 'gz@123',
        'Mobile' => $tel,
        'Content' => $content,
        'Cell' => '',
        'SendTime' => ''
    );
    $result = $client->BatchSend($sendParam);
//    file_put_contents('./sms.txt', var_export($result, true), FILE_APPEND);
    $result = $result->BatchSendResult;
    $client = null;
    return $result == 1 ? true : false;
}

/**
 * 验证验证码
 * @param $tel
 * @param $code
 * @return bool|string
 * @throws \think\Exception
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 * @throws \think\exception\PDOException
 */
function checkCode($tel, $code) {
    $data = db('code')->where(['tel'=>$tel,'is_use'=>0])->order('id desc')->find();

    if ($data['expire_time'] < time()) {
        return '验证码已过期';
    }

    if ($data['code'] != $code) {
        return '验证码错误';
    }

    db('code')->where(['id'=>$data['id']])->setField('is_use', 1);
    return true;
}

/**
 * 数组转XML
 * @param array $arr
 * @return string
 */
function arrayToXml($arr){
    $xml = "<xml>";
    foreach ($arr as $key=>$val){
        if(is_array($val)){
            $xml.="<".$key.">".$this->arrayToXml($val)."</".$key.">";
        }else{
            $xml.="<".$key.">".$val."</".$key.">";
        }
    }
    $xml.="</xml>";
    return $xml;
}

/**
 * 将XML转为array
 * @param $xml
 * @return mixed
 */
function xmlToArray($xml)
{
    //禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $values;
}

/**
 * 银行
 * @param bool $id
 * @return array|mixed|string
 */
function getBankList($id=false) {
    $list = [
        '工商银行',
        '中国银行',
        '农业银行',
        '农村商业银行',
        '邮政储蓄银行',
        '建设银行',
        '光大银行',
        '交通银行',
        '华夏银行',
        '兴业银行',
        '民生银行',
        '中信银行',
    ];
    if ($id) {
        return isset($list[$id]) ? $list[$id] : '';
    } else {
        return $list;
    }
}

/**
 * 获取提现状态
 * @param bool $status
 * @return array|mixed|string
 */
function getWithdrawState($status=false) {
    $list = [
        1 => '审核中','审核通过','审核不通过'
    ];
    if ($status) {
        return isset($list[$status]) ? $list[$status] : '未知状态';
    } else {
        return $list;
    }
}

/**
 * 获取明细记录状态
 * @param bool $status
 * @return array|mixed|string
 */
function getDetailsState($status=false) {
    $list = [
        1 => '充值',
        2 => '购买支付',
        3 => '积分转结',
        4 => '提现',
        5 => '扫码支付',
        6 => '积分收入',
        7 => '积分转结',
    ];
    if ($status) {
        return isset($list[$status]) ? $list[$status] : '未知状态';
    } else {
        return $list;
    }
}

/**
 * 获取订单状态
 * @param bool $status
 * @return array|mixed|string
 */
function getOrderState($status=false) {
    $list = [
        1 => '待付款',
        2 => '待发货',
        3 => '已发货',
        4 => '已签收',
        // 5 => '已完成',
        // 9 => '已关闭',
    ];
    if ($status) {
        return isset($list[$status]) ? $list[$status] : '未知状态';
    } else {
        return $list;
    }
}

/**
 * 获取系统参数
 * @param bool $key
 * @return mixed|string
 */
function getSystemParams($key=false) {
    $model = new \app\common\model\Param();
    $params = unserialize($model->where(['id'=>1])->value('content'));
    if ($key) {
        return isset($params[$key]) ? $params[$key] : '';
    } else {
        return $params;
    }
}

function calFxEarnings_old($amount, $user_info) {
    $params = getSystemParams();
    $user_model = new \app\common\model\User();

    /***** 一级收益开始 *****/
    if ($user_info['pid'] <= 0 || $params['percentage1'] <= 0) {
        return true;
    }
    $earnings_user = $user_model->where(['id'=>$user_info['pid']])->find();
    if (empty($earnings_user)) {
        return true;
    }
    //收益积分
    $earnings_integral = amountFormat($amount * $params['percentage1'] / 100 * $params['integral_rate']);
    if ($earnings_integral <= 0) {
        return true;
    }
    //加积分
    if ($user_model->where(['id'=>$earnings_user['id']])->setInc('integral', $earnings_integral) === false) {
        return false;
    }
    //资金记录
    $log[] = [
        'content' => '分销收入',
        'amount' => $earnings_integral,
        'add_time' => time(),
        'user_id' => $earnings_user['id'],
        'user_type' => 0,
        'type' => 6,
        'symbol' => '+',
        'balance' => $user_model->where(['id'=>$earnings_user['id']])->validate('integral')
    ];
    if (!db('details')->insertAll($log)) {
        return false;
    }
    /***** 一级收益结束 *****/

    /***** 二级收益开始 *****/
    if ($earnings_user['pid'] <= 0 || $params['percentage2'] <= 0) {
        return true;
    }
    $earnings_user = $user_model->where(['id'=>$earnings_user['pid']])->find();
    if (empty($earnings_user)) {
        return true;
    }
    //收益积分
    $earnings_integral = amountFormat($amount * $params['percentage2'] / 100 * $params['integral_rate']);
    if ($earnings_integral <= 0) {
        return true;
    }
    //加积分
    if ($user_model->where(['id'=>$earnings_user['id']])->setInc('integral', $earnings_integral) === false) {
        return false;
    }
    //资金记录
    $log[] = [
        'content' => '分销收入',
        'amount' => $earnings_integral,
        'add_time' => time(),
        'user_id' => $earnings_user['id'],
        'user_type' => 0,
        'type' => 6,
        'symbol' => '+',
        'balance' => $user_model->where(['id'=>$earnings_user['id']])->validate('integral')
    ];
    if (!db('details')->insertAll($log)) {
        return false;
    }
    /***** 二级收益结束 *****/

    /***** 二级收益开始 *****/
    if ($earnings_user['pid'] <= 0 || $params['percentage3'] <= 0) {
        return true;
    }
    $earnings_user = $user_model->where(['id'=>$earnings_user['pid']])->find();
    if (empty($earnings_user)) {
        return true;
    }
    //收益积分
    $earnings_integral = amountFormat($amount * $params['percentage3'] / 100 * $params['integral_rate']);
    if ($earnings_integral <= 0) {
        return true;
    }
    //加积分
    if ($user_model->where(['id'=>$earnings_user['id']])->setInc('integral', $earnings_integral) === false) {
        return false;
    }
    //资金记录
    $log[] = [
        'content' => '分销收入',
        'amount' => $earnings_integral,
        'add_time' => time(),
        'user_id' => $earnings_user['id'],
        'user_type' => 0,
        'type' => 6,
        'symbol' => '+',
        'balance' => $user_model->where(['id'=>$earnings_user['id']])->validate('integral')
    ];
    if (!db('details')->insertAll($log)) {
        return false;
    }
    /***** 二级收益结束 *****/

}

/**
 * 计算分销收益
 * @param $amount 金额
 * @param $user_info 用户信息
 * @return array|bool|false|PDOStatement|string|\think\Model
 * @throws \think\Exception
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function calFxEarnings($amount, $pid) {
    if ($pid <= 0 || $amount <= 0) {
        return true;
    }
    $params = getSystemParams();

    /***** 一级收益开始 *****/
    $user_info = doEarnings($pid, amountFormat($amount * $params['integral_rate'] / 100 * $params['percentage1']));
    /***** 一级收益结束 *****/

    if (is_bool($user_info)) {
        return $user_info;
    }

    /***** 二级收益开始 *****/
    $user_info = doEarnings($pid, amountFormat($amount * $params['integral_rate'] / 100 * $params['percentage2']));
    /***** 二级收益结束 *****/

    if (is_bool($user_info)) {
        return $user_info;
    }

    /***** 三级收益开始 *****/
    $user_info = doEarnings($pid, amountFormat($amount * $params['integral_rate'] / 100 * $params['percentage3']));
    /***** 三级收益结束 *****/

    return $user_info === false ? false : true;
}

/**
 * @param $amount
 * @param $pid
 * @return array|bool|false|PDOStatement|string|\think\Model
 * @throws \think\Exception
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function addPrevFxAmount($amount, $pid) {
    if ($pid <= 0 || $amount <= 0) {
        return true;
    }

    $params = getSystemParams();
    /***** 一级收益开始 *****/
    $user_info = doAdd($pid, $amount, $params);
    /***** 一级收益结束 *****/

    if (is_bool($user_info)) {
        return $user_info;
    }

    /***** 二级收益开始 *****/
    $user_info = doAdd($user_info['pid'], $amount, $params);
    /***** 二级收益结束 *****/

    if (is_bool($user_info)) {
        return $user_info;
    }

    /***** 三级收益开始 *****/
    $user_info = doAdd($user_info['pid'], $amount, $params);
    /***** 三级收益结束 *****/

    return $user_info === false ? false : true;
}

/**
 * @param $id
 * @param $amount
 * @return array|bool|false|PDOStatement|string|\think\Model
 * @throws \think\Exception
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function doAdd($id, $amount, $params) {
    if ($id <= 0) {
        return true;
    }
    $user_model = new \app\common\model\User();
    $user_info = $user_model->where(['id'=>$id])->find();
    if (empty($user_info)) {
        return true;
    }
    $user_info = $user_info->toArray();
    $db = db('history_tg');
    if ($db->where(['user_id'=>$id,'date'=>date('Y-m-d')])->count() > 0) {
        if ($db->where(['user_id'=>$id,'date'=>date('Y-m-d')])->setInc('amount', $amount) === false) {
            return false;
        }
    } else {
        $data = [
            'user_id' => $id,
            'data' => date('Y-m'),
            'amount' => $amount
        ];
        if (!$db->insert($data)) {
            return false;
        }
    }

    //奖励
    switch ($user_info['role']) {
        case 1:
            $rewards = $amount * $params['zg_percentage'] / 100 * $params['integral_rate'];
            break;
        case 2:
            $rewards = $amount * $params['jl_percentage'] / 100 * $params['integral_rate'];
            break;
        case 3:
            $rewards = $amount * $params['zj_percentage'] / 100 * $params['integral_rate'];
            break;
        default:
            $rewards = 0;
    }
    if ($rewards > 0) {
        //加积分
        if ($user_model->where(['id'=>$id])->setInc('integral', $rewards) === false) {
            return false;
        }
        //资金记录
        $log = [
            'content' => '分销奖励',
            'amount' => $rewards,
            'add_time' => time(),
            'user_id' => $id,
            'user_type' => 0,
            'type' => 6,
            'symbol' => '+',
            'balance' => $user_model->where(['id'=>$id])->value('integral')
        ];
        if (!db('details')->insert($log)) {
            return false;
        }
    }
    return $user_info;
}

/**
 * 执行收益
 * @param $pid 上级id
 * @param $earnings_integral 收益积分
 * @return array|bool|false|PDOStatement|string|\think\Model
 * @throws \think\Exception
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function doEarnings($pid, $earnings_integral) {
    if ($pid <= 0 || $earnings_integral <= 0) {
        return true;
    }
    $user_model = new \app\common\model\User();
    $earnings_user = $user_model->where(['id'=>$pid, 'user_type'=>['neq', 0]])->field('id,pid')->find();
    if (empty($earnings_user)) {
        return true;
    }
    //加积分
    if ($user_model->where(['id'=>$earnings_user['id']])->setInc('integral', $earnings_integral) === false) {
        return false;
    }
    //资金记录
    $log = [
        'content' => '分销收入',
        'amount' => $earnings_integral,
        'add_time' => time(),
        'user_id' => $earnings_user['id'],
        'user_type' => 0,
        'type' => 6,
        'symbol' => '+',
        'balance' => $user_model->where(['id'=>$earnings_user['id']])->value('integral')
    ];
    if (!db('details')->insert($log)) {
        return false;
    }
    return $earnings_user;
}

function getFxData($ids, $type=true) {
    $user_model = new \app\common\model\User();
    $order_model = new \app\common\model\Order();
    if (is_array($ids)) {
        $where = ['pid'=>['in', $ids]];
    } else {
        $where = ['pid'=>$ids];
    }
    $ids = $user_model->where($where)->column('id');
    $amount = 0;
    if (!empty($ids) && $type) {
        $amount = $order_model->where(['user_id' => ['in', $ids],'status'=>['in', [2,3,4,5]]])->sum('amount');
    }
    $data = [
        'num' => count($ids),
        'amount' => amountFormat($amount),
        'ids' => $ids
    ];
    return $data;
}

/**
 * @param $msg 弹出提示信息
 * @param int $url 跳转地址
 * @param float $time 延时跳转 秒
 */
function layerExit($msg, $url=-1, $time=1.5) {
    echo '<html><head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
    <script src="/static/index/js/jquery.min.2.1.4.js"></script>
    <script src="/static/index/js/layermobile/layer.js"></script></head><body style="background-color: #fff;">';

    if (!empty($msg)) {
        echo "<script>layer.open({content: '$msg',skin: 'msg',time: $time });</script>";
    }
    $time *= 1000;
    if (is_numeric($url)) {
        echo "<script>setTimeout(function(){window.history.go($url)}, $time);</script>";
    } else {
        echo "<script>setTimeout(function(){window.location.href = '$url'}, $time);</script>";
    }
    die('</body></html>');
}

function saveQrcode($user) {
    

    //生成二维码图
    $imgUrl = "./qrcode/invite/{$user['id']}.png" ;
    $image 	= \think\Image::open( '.' . $user['img'] );

    //缩小头像
    $image->thumb(300,300,\think\Image::THUMB_CENTER)->save($imgUrl);

    //裁剪成圆形
    circularImg( $imgUrl , $imgUrl ) ;

    //头像扒上去
    $image = \think\Image::open( './static/index/img/muban.png');
    $image->water( $imgUrl ,[485,191])->save($imgUrl);

        //添加标题
    //    $image = \think\Image::open($imgUrl);
    //    $image->text('我是' . $user['name'] ,'./qrcode/heiti.ttf',56,'#333333' ,\think\Image::WATER_NORTH , [0,470])->save( $imgUrl );

    //    //添加描述
    //    $image = \think\Image::open($imgUrl);
    //    $image->text('我为商城代言' ,'./qrcode/heiti.ttf',40,'#333333' ,\think\Image::WATER_NORTH , [0,565])->save( $imgUrl );

       //添加编号
       $image = \think\Image::open($imgUrl);
       $image->text(' 编号: '.$user['code'].' ' ,'./qrcode/heiti.ttf',36,'#333333' ,\think\Image::WATER_NORTH , [0,1300])->save( $imgUrl );
       $image->text(' 手机号: '.$user['tel'].' ' ,'./qrcode/heiti.ttf',36,'#333333' ,\think\Image::WATER_NORTH , [0,1350])->save( $imgUrl );

    //生成用户的二维码
    $qrcodeUrl = "./qrcode/invite/temp{$user['id']}.png" ;
    $qrcode = myqrcode('http://' . $_SERVER['SERVER_NAME'] . url('index/login/register', ['invite_code'=>$user['code']]), "temp{$user['id']}.png", './qrcode/invite');

    //头像扒上去
    $image = \think\Image::open( $imgUrl);
    $image->water( $qrcode ,[360,580])->save($imgUrl);

    //删除生成的二维码
    unlink( $qrcodeUrl ) ;
}
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\Db;


function is_weixin() {
    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
        return true;
    }
    return false;
}

function generate($length, $type = 1)
{
    if ($type == 1) {
        $code = rand(100000, 999999);
    } else {
        $chars = array('a', 'b', '1', 'd', 'e', '2', 'g', 'h',
            'i', '3', 'k', 'l', '4', 'n', 'o', '5', 'q', 'r', 's',
            't', 'u', '6', 'w', 'x', '7', 'z', 'c', '8', 'j', 'm',
            'p', 'v', 'y', 'f', '9');
        $keys = array_rand($chars, $length);
        $code = '';
        for ($i = 0; $i < $length; $i++) {
            $code .= $chars[$keys[$i]];
        }
    }

    $is = \app\common\model\User::where('code', $code)->count('id');
    if ($is) {
        return generate(6, $type);
    } else {
        return $code;
    }

}

function get_pay_way($vo)
{

    switch ($vo) {
        case 'bonus':
            return '奖金';
            break;
        case 'bonus1':
            return '欢笑豆';
            # code...
            break;
        case 'bonus1':
            return '欢乐豆';
        case 'balance':
            return '余额';
            # code...
            break;
        case 'wechat':
            return '微信';
            # code...
            break;
        default:
            return '其他';
            
            break;
    }
}



/**
 * 循环删除目录和文件
 * @param string $dir_name
 * @return bool
 */
function delete_dir_file($dir_name) {
    $result = false;
    if(is_dir($dir_name)){
        if ($handle = opendir($dir_name)) {
            while (false !== ($item = readdir($handle))) {
                if ($item != '.' && $item != '..') {
                    if (is_dir($dir_name . DS . $item)) {
                        delete_dir_file($dir_name . DS . $item);
                    } else {
                        unlink($dir_name . DS . $item);
                    }
                }
            }
            closedir($handle);
            if (rmdir($dir_name)) {
                $result = true;
            }
        }
    }

    return $result;
}

/**
 * @param string $NavType --导航类别 Admin/Index
 * @return string
 * 原点 2020年5月29日10:23:16 获取导航
 */
function get_navigation()
{ $controller = strtolower(request()->controller());
    
    try {
        $controller = strtolower(request()->controller());
        $action = strtolower(request()->action());
        $type = input('type');
        if($type){
            $p='type='.$type;
            $where=['controller' => $controller, 'action' => $action,'params'=>$p];
        }else{
            $where=['controller' => $controller, 'action' => $action];

        }
        $n['1'] = Db::name('link')->where($where)->field('title,pid')->find();
        if ($n['1']) {
            $n['0'] = Db::name('link')->where(['id' => $n['1']['pid']])->field('title')->find();
        }
        return $n;

    } catch (\Exception $e) {
        return $e->getMessage();
    }

}

// 应用公共文件
function subtext($text, $length)
{
    if (mb_strlen($text, 'utf8') > $length) return mb_substr($text, 0, $length, 'utf8') . '...';
    return $text;
}

function where($table, $more = [])
{
    $table_arr = explode(' ', $table);
    $table = $table_arr['0'];
    $alias = $table_arr['1'];
    if ($alias) {
        $where = [];
        foreach (config('where.' . $table) as $k => $v) {
            $where[$alias . '.' . $k] = $v;
        }
    } else {
        $where = config('where.' . $table);
    }

    return array_merge($where, $more);
}

function return_message($status, $message = '', $error = '', $url = '', $url_data = [])
{
    // if ($message != '') $message = lang($message);
    if ($status == '0' && $error != '') $message = $message . ':(' . $error . ')';
    if ($url != '') $url = url($url, $url_data);
    return ['status' => $status, 'message' => $message, 'url' => $url];
}

function article($id)
{
    return db('article')->find($id);
}

function lang($str)
{
    $lang = str_replace('-', '_', \think\Lang::range());
    $res = db('lang')->where(['keyword' => $str])->find();
    if (!$res['id']) {
        $bt = new \app\common\controller\BaiduTransapi();
        $en_us = $bt->translate($str, 'zh', 'en')['trans_result']['0']['dst'];
        $en_us = $en_us ? $en_us : $str;
        $res = [
            'keyword' => $str,
            'zh_cn' => $str,
            'en_us' => $en_us,
        ];
        db('lang')->insert($res);
    }
    return $res[$lang];
}